﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using FactoryWebApplication.Models;

namespace FactoryWebApplication.DataAccess
{
    public class FactoryDbContext:DbContext
    {
        public DbSet<SDCard> sDCards { get; set; }
        public DbSet<Machine> machines { get; set; }
        public DbSet<Chip> chips { get; set; }
        public DbSet<BatteryChip> batteryChips { get; set; }
        public DbSet<Battery> batteries { get; set; }


        public static FactoryDbContext CreateContextByConnectionString(string ConnectString)
        {
            DbContextOptions<FactoryDbContext> dbContextOption = new DbContextOptions<FactoryDbContext>();
            DbContextOptionsBuilder<FactoryDbContext> dbContextOptionBuilder = new DbContextOptionsBuilder<FactoryDbContext>(dbContextOption);

            return new FactoryDbContext(dbContextOptionBuilder.UseMySQL(ConnectString).Options);
        }

        public FactoryDbContext(DbContextOptions options) : base(options) { }


        protected sealed override void OnModelCreating(ModelBuilder mb)
        {
            base.OnModelCreating(mb);

            mb.Entity<SDCard>(b =>
            {
                b.HasKey(x => x.Id);
                b.ToTable("T_SDCard");
            });

            mb.Entity<Machine>(b => 
            {
                b.HasKey(x => x.Code);
                b.ToTable("T_Machine");
            });

            mb.Entity<Chip>(b=>
            {
                b.HasKey(x => x.Code);
                b.ToTable("T_Chip");
            });
            mb.Entity<BatteryChip>(b => 
            {
                b.HasKey(x => x.Code);
                b.ToTable("T_BatteryChip");
            });
            mb.Entity<Battery>(b =>
            {
                b.HasKey(x => x.Code);
                b.ToTable("T_Battery");
            });


        }

        /// <summary>
        /// 追加处理数据模型生成事件。
        /// </summary>
        public event EventHandler<ModelBuilder> ExtendModelCreating;

        /// <summary>
        /// 追加处理数据模型生成方法。
        /// </summary>
        /// <param name="mb">数据模型生成器对象实例。</param>
        protected virtual void OnExtendModelCreating(ModelBuilder mb)
        {
            if (ExtendModelCreating != null) ExtendModelCreating.Invoke(this, mb);
        }
    }
}
